<template>
	<view class="pageBox">
		<view class="topTipBox">
			<view class="title">报修说明</view>
			<view class="text">说明：将为广大人才提供物业报修服务</view>
		</view>
		<view class="gapBox"></view>
		<view class="formBox">
			<u--form labelPosition="left" :model="formData" labelWidth="160rpx" :rules="rules" ref="uForm">
				<view class="formItemBox">
					<!-- <u-form-item label="小区" borderBottom>
						<u--input v-model="roomData.title" readonly border="none" placeholder="请输入小区" dis></u--input>
					</u-form-item>
					<u-form-item label="楼栋" borderBottom>
						<u--input v-model="roomData.buildingName" readonly border="none" placeholder="请输入楼栋"></u--input>
					</u-form-item>
					<u-form-item label="房号" borderBottom>
						<u--input v-model="roomData.roomNumber" readonly border="none" placeholder="请输入房号"></u--input>
					</u-form-item> -->
					<u-form-item label="联系人" borderBottom>
						<view class="inputView">
							{{userInfo.nickName}}
						</view>
					</u-form-item>
					<u-form-item label="联系方式" borderBottom>
						<view class="inputView">
							{{userInfo.phonenumber}}
						</view>
					</u-form-item>
					<!-- <u-form-item label="预约时间" prop="reservationTimer" borderBottom
						@click="openTime('timeShow','reservationTimer')">
						<view class="placeholderText" v-if="!formData.reservationTimer">请选择预约时间</view>
						<view class="inputView" v-else>
							{{setWeek(formData.reservationTimer)}}
						</view>
					</u-form-item> -->
					<u-form-item label="报修事项" prop="matter" borderBottom>
						<u--input v-model="formData.matter" border="none" placeholder="请输入报修事项"></u--input>
					</u-form-item>
					<u-form-item label="拍照" prop="guaranteePicture" borderBottom>
						<u-upload width="160rpx" height="160rpx" :fileList="fileList"
							@afterRead="afterRead($event, 'fileList')" @delete="deletePic($event, 'fileList')" multiple
							accept="image">
						</u-upload>
					</u-form-item>
					<u-form-item label="视频" prop="guaranteeVideo" borderBottom>
						<u-upload width="160rpx" height="160rpx" :fileList="fileList1"
							@afterRead="afterRead($event, 'fileList1')" @delete="deletePic($event, 'fileList1')"
							multiple accept="video">
						</u-upload>
					</u-form-item>
				</view>
				<view class="gapBox"></view>
				<view class="formItemBox">
					<u-form-item label="备注" prop="remark">
						<u--textarea v-model="formData.remark" placeholderClass="plText" placeholder="请输入备注" autoHeight
							border="none"></u--textarea>
					</u-form-item>
				</view>
				<view class="btnBox">
					<view class="btn" @click="submit">提交</view>
				</view>
			</u--form>
			<!-- 	<u-picker :show="show" :columns="[dictList.handle_type]" keyName="label" title="代办类型"
				@confirm="confirmPicker1($event,'show')" @cancel="closePicker('show')"
				@close="closePicker('show')"></u-picker> -->
			<u-datetime-picker :minDate="-4607395543000" ref="datetimePicker" title="预约时间" :show="timeShow"
				v-model="time" mode="date" :formatter="formatter" @confirm="confirmPicker($event,'timeShow')"
				@cancel="closePicker('timeShow')" @close="closePicker('timeShow')"></u-datetime-picker>
		</view>
	</view>
</template>

<script>
	import {
		formatTime
	} from "@/utils/util.js"
	import * as guaranteeApi from "@/api/serve/guarantee.js"
	import * as systemApi from "@/api/system.js"
	import * as uploadApi from "@/api/upload.js"
	import {
		apartmentTenant
	} from "@/api/room.js"
	export default {
		data() {
			return {
				show: false,
				timeShow: false,
				time: Number(new Date()),
				IMGMaxSize: 1024 * 1024 * 5,
				fileList: [],
				fileList_imgs: [],
				fileList_old: [],
				fileList1: [],
				fileList1_imgs: [],
				fileList1_old: [],
				fileList2: [],
				roomData: {
					// apartmentId: null,
					apartmentName: null,
					attachment: null,
					availability: null,
					// buildingId: null,
					buildingName: null,
					capacity: null,
					floors: null,
					// houseId: null,
					rent: null,
					roomNumber: null,
					squareMeter: null,
					talent: null,
					tenant: null,
					title: null
				},
				eliteInfo: null,
				userInfo: {
					nickName: '',
					phonenumber: ''
				},
				formData: {
					// reservationTimer: '',
					address: '',
					matter: '',
					guaranteePicture: '',
					guaranteeVideo: '',
					remark: ''
				},
				rules: {
					'reservationTimer': {
						type: 'number',
						required: true,
						message: '请选择预约时间',
						trigger: ['blur', 'change']
					},
					'address': {
						type: 'string',
						required: true,
						message: '请输入小区',
						trigger: ['blur', 'change']
					},
					'matter': {
						type: 'string',
						required: true,
						message: '请输入报修事项',
						trigger: ['blur', 'change']
					},
					// 'guaranteePicture': {
					// 	type: 'string',
					// 	required: true,
					// 	message: '请上传照片',
					// 	trigger: ['blur', 'change']
					// },
				},
				dicts: {
					handle_type: {}
				},
				dictList: {
					handle_type: []
				},
			};
		},
		onReady() {
			// 微信小程序需要用此写法
			this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		onShow() {
			this.userInfo = this.$store.getters.my_userInfo
			this.eliteInfo = this.$store.getters.eliteInfo
			if (!this.userInfo || !this.eliteInfo) {
				this.$store.dispatch('userBaseInfo').then(res => {
					this.userInfo = res.user
					this.eliteInfo = res.eliteInfo
				})
			}
		},
		onLoad() {
			// this.getDictDataList('handle_type')
			// this.getRoomData()
		},
		methods: {
			uploadFile(file) {
				return new Promise((resolve, reject) => {
					const formData = new FormData();
					formData.append('file', file);
					uploadApi
						.upload(url)
						.then((
							data
						) => {
							const {
								fileName,
								newFileName,
								originalFilename,
								url
							} = data
							const imgData = {
								fileName,
								newFileName,
								originalFilename,
								url
							}
							if (Object.prototype.toString.call(this[dataStr + '_imgs']) ===
								'[object Array]') {
								this[dataStr + '_imgs'].push(imgData)
							} else if (Object.prototype.toString.call(this[dataStr + '_imgs']) ===
								'[object String]') {
								this[dataStr + '_imgs'] = imgData
							}
							resolve(imgData)
						})
						.catch(reject)
				});
			},
			getRoomData() {
				apartmentTenant().then(res => {
					this.roomData = res.data
				})
			},
			// 删除图片
			deletePic(event, dataStr) {
				this[dataStr].splice(event.index, 1)
				if (typeof(this[dataStr + '_imgs']) === 'string') {
					this[dataStr + '_imgs'] = ''
				} else {
					this[dataStr + '_imgs'].splice(event.index, 1)
				}
			},
			beforeRead(file, lists) {
				// const {
				// 	name,
				// 	size,
				// 	type
				// } = file
				const imgTypes = ['bmp', 'jpg', 'png', 'jpeg']
				const IMGMaxSize = this.IMGMaxSize
				file.forEach(item => {
					const isJPG = imgTypes.indexOf(item.type) !== -1;
					const sizeT = item.size <= IMGMaxSize
				})
				return sizeT && isJPG
			},
			// 新增图片
			async afterRead(event, dataStr) {
				const that = this
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[dataStr].length
				//备份 失败回调
				that[dataStr + '_old'] = JSON.parse(JSON.stringify(that[dataStr]))
				lists.map(item => {
					that[dataStr].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await that
						.uploadFilePromise(lists[i].url, dataStr)
						.then(res => {
							return res
						})
						.catch(() => {
							// that[dataStr] = that[dataStr + '_old']
							return false
						})
					if (result) {
						let item = that[dataStr][fileListLen]
						that[dataStr].splice(
							fileListLen,
							1,
							Object.assign(item, {
								status: 'success',
								message: '',
								url: result.url
							})
						)
						fileListLen++
					} else {
						let item = that[dataStr][fileListLen]
						that[dataStr].splice(
							fileListLen,
							1
						)
					}
					that[dataStr + '_old'] = JSON.parse(JSON.stringify(that[dataStr]))
				}
			},
			uploadFilePromise(url, dataStr) {
				return new Promise((resolve, reject) => {
					uploadApi
						.upload(url)
						.then((
							data
						) => {
							const {
								fileName,
								newFileName,
								originalFilename,
								url
							} = data
							const imgData = {
								fileName,
								newFileName,
								originalFilename,
								url
							}
							if (Object.prototype.toString.call(this[dataStr + '_imgs']) ===
								'[object Array]') {
								this[dataStr + '_imgs'].push(imgData)
							} else if (Object.prototype.toString.call(this[dataStr + '_imgs']) ===
								'[object String]') {
								this[dataStr + '_imgs'] = imgData
							}
							resolve(imgData)
						})
						.catch(reject)
				})
			},
			getDictDataList(dictType) {
				return new Promise((resolve, reject) => {
					systemApi.dictDataList(dictType).then(({
						rows
					}) => {
						let objs = {}
						let keyValues = []
						rows.forEach((item) => {
							objs[item.dictValue] = item.dictLabel
							keyValues.push({
								label: item.dictLabel,
								text: item.dictLabel,
								value: item.dictValue
							})
						})
						this.dicts[dictType] = objs
						this.dictList[dictType] = keyValues
						resolve({
							objs,
							keyValues,
							rows
						})
					}).catch(reject)
				})
			},
			confirmPicker1({
				value
			}, showName) {
				const timeName = this.timeName
				this.formData[timeName] = value[0].value
				this.formData[timeName + 'Label'] = value[0].label
				this[showName] = false
			},
			confirmPicker({
				value,
				mode
			}, showName) {
				const timeName = this.timeName
				this.formData[timeName] = value
				this[showName] = false
			},
			closePicker(show) {
				this[show] = false
				this.timeName = ''
			},
			openTime(show, timeName) {
				this[show] = true
				this.timeName = timeName
			},
			closeTime(show, timeName) {
				this[show] = false
				this.timeName = ''
			},
			setWeek(value) {
				const dateTime = formatTime(new Date(value), '-')
				return `${dateTime.time1}`
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			submit() {
				const that = this
				if (this.fileList.length > 0) {
					this.formData.guaranteePicture = JSON.stringify(this.fileList)
				}
				if (this.fileList1.length > 0) {
					this.formData.guaranteeVideo = JSON.stringify(this.fileList1)
				}
				const formData = JSON.parse(JSON.stringify(this.formData))
				// formData.reservationTimer = formatTime(formData.reservationTimer, "-").time1
				const {
					apartmentId,
					houseId,
					buildingId,
					buildingName,
					roomNumber,
					title
				} = this.roomData
				// formData.apartmentId = apartmentId
				// formData.houseId = houseId
				// formData.buildingId = buildingId
				// formData.address = `${title}${buildingName}${roomNumber}`
				this.$refs.uForm.validate().then(res => {
					uni.$u.throttle(
						guaranteeApi.addguarantee(formData).then(res => {
							that.$toast1("提交成功", setTimeout(() => {
								that.$navTo(
									'pages/my/serve/repair/repairList/repairList', {},
									'redirectTo')
							}, 600))
						}), 500)
				}).catch(errors => {
					// uni.$u.toast('校验失败')
					this.formData.guaranteePicture = ''
					this.formData.guaranteeVideo = ''
				})
			}
		},
	}
</script>

<style lang="scss" scoped>
	@import "@/pages/my/server.scss";

	/deep/.plText {
		font-size: 28rpx;
		color: #979797
	}
</style>